/**
 * <br>项目名: test
 * <br>文件名: PhotoUtils.java
 * <br>Copyright 2015 恒昌互联网运营中心
 */
package com.credithc.fastdfs.photo.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Properties;

import org.apache.commons.io.FileUtils;
import org.im4java.core.CommandException;
import org.im4java.core.ConvertCmd;
import org.im4java.core.IM4JavaException;
import org.im4java.core.IMOperation;
import org.im4java.core.IdentifyCmd;
import org.im4java.process.ArrayListOutputConsumer;

import com.credithc.fastdfs.util.PathUtil;

/**
 * <br>
 * 类 名: PhotoUtils <br>
 * 描 述: 描述类完成的主要功能 <br>
 * 作 者: zj <br>
 * 创 建： 2015年5月12日 <br>
 * 版 本：v1.0.0 <br>
 * <br>
 * 历 史: (版本) 作者 时间 注释
 */
public class PhotoUtils {

	private static boolean isWindows = false;
	private static String GM_PATH = "";
	static {
		String osName = System.getProperty("os.name");
		if (osName.toLowerCase().indexOf("windows") > -1) {
			isWindows = true;
			Properties props = new Properties();
			try {
				
				File file = new File(PathUtil.getClassPath() + "property/photoConfig.properties");
				
				InputStream in=null;
				if(file.exists()){
					in = new FileInputStream(file);
				}else{
					in= PhotoUtils.class.getClassLoader().getResourceAsStream("photoConfig.properties");
				}
				
				props.load(in);
			} catch (FileNotFoundException e) {
				System.err.println("找不到配置文件photoConfig.properties！！");
				
				
				
			} catch (IOException e) {
				System.err.println("读取配置文件photoConfig.properties错误！！");
				e.printStackTrace();
			}
			GM_PATH = (String) props.get("gmPath");
		}
	}

	/**
	 * 获取IdentifyCmd
	 * 
	 * @return
	 */
	private static IdentifyCmd getIdentifyCmd() {
		IdentifyCmd identifyCmd = new IdentifyCmd(true);
		if (isWindows) {
			identifyCmd.setSearchPath(GM_PATH);
		}
		return identifyCmd;
	}

	/**
	 * 获取ConvertCmd
	 * 
	 * @return
	 */
	private static ConvertCmd getConvertCmd() {
		ConvertCmd convertCmd = new ConvertCmd(true);
		if (isWindows) {
			convertCmd.setSearchPath(GM_PATH);
		}
		return convertCmd;
	}

	public static int getSize(String imagePath) {
		int size = 0;
		FileInputStream inputStream = null;
		try {
			inputStream = new FileInputStream(imagePath);
			size = inputStream.available();
			inputStream.close();
			inputStream = null;
		} catch (FileNotFoundException e) {
			size = 0;
			System.out.println("文件未找到!");
		} catch (IOException e) {
			size = 0;
			System.out.println("读取文件大小错误!");
		} finally {
			// 可能异常为关闭输入流,所以需要关闭输入流
			if (null != inputStream) {
				try {
					inputStream.close();
				} catch (IOException e) {
					System.out.println("关闭文件读入流异常");
				}
				inputStream = null;

			}
		}
		return size;
	}

	/**
	 * 获得图片的宽度
	 * 
	 * @param filePath
	 *            文件路径
	 * @return 图片宽度
	 */
	public static int getWidth(String imagePath) {
		int line = 0;
		IMOperation op = new IMOperation();
		try {
			op.format("%w"); // 设置获取宽度参数
			op.addImage(1);
			ArrayListOutputConsumer output = new ArrayListOutputConsumer();
			IdentifyCmd identifyCmd = getIdentifyCmd();
			identifyCmd.setOutputConsumer(output);
			identifyCmd.run(op, imagePath);
			ArrayList<String> cmdOutput = output.getOutput();
			assert cmdOutput.size() == 1;
			line = Integer.parseInt(cmdOutput.get(0));
		} catch (Exception e) {
			line = 0;
			System.out.println("运行指令出错!");
			e.printStackTrace();
		}finally{
			op.closeOperation();
		}
		return line;
	}

	/**
	 * 获得图片的高度
	 * 
	 * @param imagePath
	 *            文件路径
	 * @return 图片高度
	 */
	public static int getHeight(String imagePath) {
		int line = 0;
		IMOperation op = new IMOperation();
		try {

			op.format("%h"); // 设置获取高度参数
			op.addImage(1);
			ArrayListOutputConsumer output = new ArrayListOutputConsumer();
			IdentifyCmd identifyCmd = getIdentifyCmd();
			identifyCmd.setOutputConsumer(output);
			identifyCmd.run(op, imagePath);
			ArrayList<String> cmdOutput = output.getOutput();
			assert cmdOutput.size() == 1;
			line = Integer.parseInt(cmdOutput.get(0));
		} catch (Exception e) {
			line = 0;
			System.out.println("运行指令出错!" + e.toString());
		}finally{
			op.closeOperation();
		}
		return line;
	}

	/**
	 * 图片信息
	 * 
	 * @param imagePath
	 * @return
	 */
	public static String getImageInfo(String imagePath) {
		String line = null;
		IMOperation op = new IMOperation();
		try {
			op.format("width:%w,height:%h,path:%d%f,size:%b%[EXIF:DateTimeOriginal]");
			op.addImage(1);
			ArrayListOutputConsumer output = new ArrayListOutputConsumer();
			IdentifyCmd identifyCmd = getIdentifyCmd();
			identifyCmd.setOutputConsumer(output);
			identifyCmd.run(op, imagePath);
			ArrayList<String> cmdOutput = output.getOutput();
			assert cmdOutput.size() == 1;
			line = cmdOutput.get(0);

		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			op.closeOperation();
		}
		return line;
	}

	/**
	 * 裁剪图片
	 * 
	 * @param imagePath
	 *            源图片路径
	 * @param newPath
	 *            处理后图片路径
	 * @param x
	 *            起始X坐标
	 * @param y
	 *            起始Y坐标
	 * @param width
	 *            裁剪宽度
	 * @param height
	 *            裁剪高度
	 * @return 返回true说明裁剪成功,否则失败
	 */
	public static boolean cutImage(String imagePath, String newPath, int x, int y, int width, int height) {
		boolean flag = false;
		IMOperation op = new IMOperation();
		try {
			op.addImage(imagePath);
			/** width：裁剪的宽度 * height：裁剪的高度 * x：裁剪的横坐标 * y：裁剪纵坐标 */
			op.crop(width, height, x, y);
			op.addImage(newPath);
			ConvertCmd convert = getConvertCmd();
			convert.run(op);
			flag = true;
		} catch (IOException e) {
			System.out.println("文件读取错误!");
			flag = false;
		} catch (InterruptedException e) {
			flag = false;
		} catch (IM4JavaException e) {
			flag = false;
		} finally {
			op.closeOperation();
		}
		return flag;
	}

	/**
	 * 根据尺寸缩放图片[等比例缩放:参数height为null,按宽度缩放比例缩放;参数width为null,按高度缩放比例缩放]
	 * 
	 * @param imagePath
	 *            源图片路径
	 * @param newPath
	 *            处理后图片路径
	 * @param width
	 *            缩放后的图片宽度
	 * @param height
	 *            缩放后的图片高度
	 * @return 返回true说明缩放成功,否则失败
	 */
	public static boolean zoomImage(String imagePath, String newPath, Integer width, Integer height) {

		boolean flag = false;
		IMOperation op = new IMOperation();
		try {
			op.addImage(imagePath);
			if (width == null) {// 根据高度缩放图片
				op.resize(null, height);
			} else if (height == null) {// 根据宽度缩放图片
				op.resize(width);
			} else {
				op.resize(width, height);
			}
			op.addImage(newPath);
			ConvertCmd convert = getConvertCmd();
			convert.run(op);
			flag = true;
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("文件读取错误!");
			flag = false;
		} catch (InterruptedException e) {
			e.printStackTrace();
			flag = false;
		} catch (IM4JavaException e) {
			e.printStackTrace();
			flag = false;
		} finally {
			op.closeOperation();
		}
		return flag;
	}

	/**
	 * 图片旋转
	 * 
	 * @param imagePath
	 *            源图片路径
	 * @param newPath
	 *            处理后图片路径
	 * @param degree
	 *            旋转角度
	 */
	public static boolean rotate(String imagePath, String newPath, double degree) {
		boolean flag = false;
		try {
			// 1.将角度转换到0-360度之间
			degree = degree % 360;
			if (degree <= 0) {
				degree = 360 + degree;
			}
			IMOperation op = new IMOperation();
			op.addImage(imagePath);
			op.rotate(degree);
			op.addImage(newPath);
			ConvertCmd convertCmd = getConvertCmd();
			convertCmd.run(op);
			flag = true;
		} catch (Exception e) {
			flag = false;
			System.out.println("图片旋转失败!");
		}
		return flag;
	}


	public static File getTmpFile(String suffix) throws IOException {
		File tmpFile = File.createTempFile("photoUtil-", suffix);
		tmpFile.deleteOnExit();
		return tmpFile;
	}

	public static void main(String[] args) throws Exception {

		System.out.println("原图片大小:" + PhotoUtils.getSize("c://1.png") + " bit");
		System.out.println("原图片宽度:" + PhotoUtils.getWidth("c://1.png"));
		System.out.println("原图片高度:" + PhotoUtils.getHeight("c://1.png"));
		if (PhotoUtils.zoomImage("c://1.png", "c://3.png", 200, null)) {
			if (PhotoUtils.rotate("c://1.png", "c://4.png", 15)) {
				if (PhotoUtils.cutImage("c://1.png", "c://5.png", 32, 105, 200, 200)) {
					System.out.println("编辑成功");
				} else {
					System.out.println("编辑失败03");
				}
			} else {
				System.out.println("编辑失败02");
			}
		} else {
			System.out.println("编辑失败01");
		}
	}
}
